package com.itheima.contorller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domain.Category;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    //添加
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
       dishService.saveWithFlavor(dishDto);
        //清除某个分类下的菜品缓存数据
        String keys="dish_"+dishDto.getCategoryId()+dishDto.getStatus();
        redisTemplate.delete(keys);
       return R.success("添加成功");
    }
   //分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        Page<Dish> dishpage = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> dishpageLambdaQueryWrapper = new LambdaQueryWrapper<>();

        dishpageLambdaQueryWrapper.like(Strings.isNotEmpty(name),Dish::getName,name);
        dishpageLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(dishpage,dishpageLambdaQueryWrapper);
        BeanUtils.copyProperties(dishpage,dishDtoPage,"records");

        List<Dish> records = dishpage.getRecords();

       List<DishDto> list= records.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            String name1 = byId.getName();
            dishDto.setCategoryName(name1);
          return dishDto;

        }).collect(Collectors.toList());
       dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);

    }
    //根据id回显数据
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto byIdFlavor = dishService.getByIdFlavor(id);
        return R.success(byIdFlavor);
    }
   //修改功能
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){

        dishService.updatee(dishDto);
        //清理所有菜品的缓存数据
//        Set keys = redisTemplate.keys("dish_*");
        //清除某个分类下的菜品缓存数据
        String keys="dish_"+dishDto.getCategoryId()+dishDto.getStatus();
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }
   //批量禁用和启用

   @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status,@RequestParam List<Long> ids){
       log.info("status:{}",status);
       log.info("ids:{}",ids);
       LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
       dishLambdaQueryWrapper.in(ids != null,Dish::getId,ids);
       List<Dish> list = dishService.list(dishLambdaQueryWrapper);

       for (Dish dish : list) {
           if (dish!=null){
               dish.setStatus(status);
               dishService.updateById(dish);
           }

       }
       return R.success("修改成功");


    }
    //删除和批量删除
    @DeleteMapping
    public R<String> deleteById(Long[] ids){


        for (Long id : ids) {
            dishService.removeById(id);
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.in(DishFlavor::getDishId,ids);
            dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        }
        return R.success("删除成功");
    }
    //套餐管理里面添加菜品中的回显
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dis){
        List<DishDto> lists=null;

        String key="dish_"+dis.getCategoryId()+dis.getStatus();
        //先从redis缓存中获取缓存数据
        lists = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (lists!=null){
            return R.success(lists);
        }

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(dis.getCategoryId()!=null,Dish::getCategoryId,dis.getCategoryId());
        dishLambdaQueryWrapper.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);


       lists= list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            String name1 = byId.getName();
            dishDto.setCategoryName(name1);

            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> dishDtoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishDtoLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
            List<DishFlavor> list1 = dishFlavorService.list(dishDtoLambdaQueryWrapper);
            dishDto.setFlavors(list1);
            return dishDto;

        }).collect(Collectors.toList());

         redisTemplate.opsForValue().set(key,list,60, TimeUnit.MINUTES);
        return R.success(lists      );

    }
}
